package com.lhj.security.config.security;

import com.google.common.cache.Cache;
import com.lhj.security.entity.UserEntity;
import com.lhj.security.exception.PasswordMismatchException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author lhj
 * @Date 2024/12/27 9:23
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Resource
    private Cache<String, UserEntity> userCache;
    
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userCache.getIfPresent(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("user not fond username " + username);
        }
        validated(userEntity.getPassword());
        return new UserAuthDetail(userEntity);
    }

    private void validated(String password) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContextHolder();
        String rawPassword = usernamePasswordAuthenticationToken.getCredentials().toString();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(rawPassword, password);
        if (!matches) {
            log.error("用户登陆-密码校验错误，登陆用户名: {}", usernamePasswordAuthenticationToken.getPrincipal().toString());
            throw new PasswordMismatchException("用户密码不正确！");
        }
    }
}
